package com.sharedmobility.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    // 数据库连接参数
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/gongxiang?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    static {
        try {
            // 注册JDBC驱动
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            System.err.println("加载MySQL驱动失败：" + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("加载MySQL驱动失败", e);
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException {
        try {
            return DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            System.err.println("获取数据库连接失败：" + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.err.println("关闭数据库连接失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }
} 